import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import toNative from '@/utils/toNative'
import { Component, Emit } from 'vue-facing-decorator'

import RenderDescription, { type DescItemDto } from '@/components/render-descriotion/Index'
import { VxeColumn, VxeGrid, VxeTable, type VxeTableDataRow } from 'vxe-table'
import { queryConfigDetail } from '@/api/emailConfig'
import type { CommunicationConfigDto } from '@/api/emailConfig/types'
import type { TableChildrenDto } from '../components/ApiPushRule'
import PreviewExcel from '@/components/preview-media/PreviewExcel'
import { IsSetUserDetailConfigTypeCnEnum } from '@/const/enum'

export function getHttpConfigData(httpData: string) {
    const configData = JSON.parse(httpData)
    const res = []
    for (const key in configData.properties) {
        const items =
                    configData.properties[key]?.items?.properties ||
                    configData.properties[key]?.properties ||
                    {} // type 为array 或是 object取里面的属性
        const tempData = {
            type: configData.properties[key].type,
            originPhrase: '',
            originPhraseName: '',
            mapPhrase: '',
            children: [] as TableChildrenDto[]
        }
        switch (configData.properties[key].type) {
        case 'string':
            res.push({
                type: 'string',
                originPhrase: key,
                originPhraseName: configData.properties[key].mapping,
                mapPhrase: configData.properties[key].mappingName,
                children: []
            })
            break
        case 'array':
        case 'object':
            tempData.originPhrase = key
            for (const k in items) {
                tempData.children.push({
                    originPhrase: k,
                    originPhraseName: items[k].mapping,
                    mapPhrase: items[k].mappingName
                })
            }
            res.push(tempData)
        }
    }
    return res
}

@Component
export class Detail extends TableRender {
    id = null as null | number

    showDrawer = false
    detail = {} as CommunicationConfigDto

    get descData() {
        return [
            {
                label: '规则名称',
                value: this.detail.ruleName
            },
            {
                label: '保险产品',
                value: '长期保' //暂时只有长期保
            }
        ] as DescItemDto[]
    }

    get apiData() {
        const httpConfig = this.detail.httpConfig?.[0] ?? {} // 当前只有一个默认去第0个就行
        return [
            {
                label: '数据推送地',
                value: httpConfig.url,
                span: 2
            },
            {
                label: '密钥',
                value: httpConfig.secretKey
            },
            {
                label: '授权码',
                value: httpConfig.authCode
            }
        ] as DescItemDto[]
    }

    get mapData() {
        const httpConfig = this.detail.httpConfig?.[0] ?? {}
        if (httpConfig.respConfig) {
            return getHttpConfigData(httpConfig.respConfig)
        }
        return []
    }

    @Emit('refresh')
    handleRefresh() {}

    treeConfig = {
        childrenField: 'children',
        expandAll: true
    }

    columns = [
        {
            field: 'originPhrase',
            title: '原始字段',
            treeNode: true
        },
        {
            field: 'originPhraseName',
            title: '原始字段名称',
        },
        {
            field: 'mapPhrase',
            title: '映射字段',
        },
    ]

    async initData() {
        const res = await queryConfigDetail({
            id: this.id as number
        })
        this.detail = res
    }

    mounted() {
        if (this.$route.params?.id) {
            this.id = parseInt(this.$route.params.id as string)
            this.initData()
        }
    }

    render() {
        return (
            <div class="px-24px py-16px">
                <div class="text-lg font-bold mb-20px">保司规则预览</div>
                <div>
                    <RenderDescription row={2} renderData={this.descData} />
                    <div class="text-lg mt-24px mb-16px">邮件规则</div>
                    <VxeTable border="none" data={this.detail.emailConfig ?? []}>
                        <VxeColumn field="fileTemplate" title="邮件模板" v-slots={{
                            default: () => {
                                const list = this.detail.emailConfig?.[0].fileTemplate?.split(';') ?? []
                                console.log(111, list)
                                return (
                                    list.length ?
                                        list.map(i => {
                                            return <PreviewExcel src={i}></PreviewExcel>
                                        })
                                        :
                                        '--'
                                )
                            }
                        }}>

                        </VxeColumn>
                        <VxeColumn field="emailTitleTemplate" title="邮件标题"></VxeColumn>
                        <VxeColumn field="emailTextTemplate" title="邮件正文"></VxeColumn>
                        <VxeColumn field="emailTo" title="邮件地址"></VxeColumn>
                    </VxeTable>
                    <div class="flex">
                        <div class="text-black-300 flex-shrink-0">客户清单：</div>
                        <div class="flex-1">
                            <div><span> {Number(this.detail.coInsureType) === IsSetUserDetailConfigTypeCnEnum.配置 ? '需要' : '不需要'}</span>发送新增客户清单<span>{Number(this.detail.coInsureType) === IsSetUserDetailConfigTypeCnEnum.配置 ? `，每天${this.detail.coInsureTime}发送;` : ''} </span></div>
                            {
                                Number(this.detail.coInsureType) === IsSetUserDetailConfigTypeCnEnum.配置 ? 
                                    <div class="bg-fill px-16px py-12px rounded-m mt-8px">
                                        <div class="flex">
                                            <div class="text-black-300 flex-shrink-0">邮箱地址：</div>
                                            <div class="flex-1">{this.detail.coInsureEmail}</div>
                                        </div>
                                    </div>: <></>
                            }
                        </div>
                    </div>
                    <div>
                        <div class="text-lg mt-24px mb-16px">API推送规则</div>
                        <RenderDescription row={2} renderData={this.apiData} />
                    </div>
                    <div>
                        <div class="text-lg mt-24px mb-16px">映射关系</div>
                        <VxeGrid
                            treeConfig={this.treeConfig}
                            columns={this.columns}
                            data={this.mapData}
                        ></VxeGrid>
                    </div>
                </div>
            </div>
        )
    }
}

export default toNative<{ id: number }, { refresh: () => void }>(Detail)
